package com.juyu.miliao.authentication.security;

import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.security.exception.IllegalVerificationCodeFormatException;
import com.juyu.miliao.common.util.IpUtil;
import com.juyu.miliao.common.util.VerifyUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 一键登录
 *
 * @author wbf
 */
public class AutomaticLogonRegisterFilter extends AbstractAuthenticationProcessingFilter {

    public AutomaticLogonRegisterFilter(String filterProcessesUrl) {
        super(new AntPathRequestMatcher(filterProcessesUrl, "POST"));
    }

    public AutomaticLogonRegisterFilter() {
        super(new AntPathRequestMatcher("/login/automatic", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //验证设备号
        String deviceNo = request.getParameter("deviceNo");
        if (deviceNo == null || deviceNo.equals(""))
            throw new IllegalVerificationCodeFormatException("deviceNo:" + deviceNo);

        CommonHead com = VerifyUtil.verifyCommonHead(request);

        //获取ip
        String ip = IpUtil.getIPv4Address(request);

        AutomaticLogonRegisterToken authRequest = new AutomaticLogonRegisterToken(deviceNo, ip, com);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

}
